package com.sl.au.controller;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

import net.sf.json.JSONObject;

import org.springframework.web.bind.annotation.PathVariable;
//import org.json.JSONObject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

@RestController
@RequestMapping(value = "/ui/CommercialTenant") 
public class CommercialTenantController extends BaseController {

	// 凭证获取（GET）——access_token  
    public final static String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";  
    // 微信JSSDK的ticket请求URL地址——jsapi_ticket  
    public final static String JSAPI_TICKET_URL = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=ACCESS_TOKEN"; 
    
    //获取永久二维码地址
    public final static String PERMANENT_URL = "{\"action_name\": \"QR_LIMIT_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": sceneid}}}}";
    //临时二维码地址
    
    public final static String appid="wxa15022a2ba45b622";
    public final static String appsecret="b01453e22593bc5bcea78534bdf8861d";
   
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index() {
		
		ModelAndView modelAndView = this.createLayoutView("CommercialTenant/CommercialTenantindex");
		return modelAndView;
	}
	public JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {  
        JSONObject jsonObject = null;  
        StringBuffer buffer = new StringBuffer();  
        try {  
            URL url = new URL(requestUrl);  
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();  
  
            httpUrlConn.setDoOutput(true);  
            httpUrlConn.setDoInput(true);  
            httpUrlConn.setUseCaches(false);  
            // 设置请求方式（GET/POST）  
            httpUrlConn.setRequestMethod(requestMethod);  
  
            if ("GET".equalsIgnoreCase(requestMethod))  
                httpUrlConn.connect();  
  
            // 当有数据需要提交时  
            if (null != outputStr) {  
                OutputStream outputStream = httpUrlConn.getOutputStream();  
                // 注意编码格式，防止中文乱码  
                outputStream.write(outputStr.getBytes("UTF-8"));  
                outputStream.close();  
            }  
  
            // 将返回的输入流转换成字符串  
            InputStream inputStream = httpUrlConn.getInputStream();  
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");  
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  
  
            String str = null;  
            while ((str = bufferedReader.readLine()) != null) {  
                buffer.append(str);  
            }  
            bufferedReader.close();  
            inputStreamReader.close();  
            // 释放资源  
            inputStream.close();  
            inputStream = null;  
            httpUrlConn.disconnect();
            jsonObject =net.sf.json.JSONObject.fromObject(buffer.toString());  
        } catch (ConnectException ce) {  
        } catch (Exception e) {  
        }  
        return jsonObject;  
    }
	
	@RequestMapping(value="GetAccessToken",method = RequestMethod.GET)
	public Map<String, Object> GetAccessToken(){
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("code", 1);
		 String url = ACCESS_TOKEN_URL.replace("APPID", appid).replace("APPSECRET", appsecret); 
		 JSONObject jsonObject = this.httpRequest(url,"GET",null);
		 if(jsonObject!=null)
		 {
			 map.put("code", 1);
		 } 
		 map.put("access_token", jsonObject.get("access_token"));
		 map.put("expires_in", jsonObject.get("expires_in"));
		 return map;
	}
	@RequestMapping(value="GetTicket/{access_token}",method = RequestMethod.GET)
	public Map<String, Object> GetTicket(@PathVariable String access_token){
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("code", 1);
		String url =JSAPI_TICKET_URL.replace("ACCESS_TOKEN", access_token);
		String  permanent_url= PERMANENT_URL.replace("sceneid", "1");
		JSONObject jsonObject = this.httpRequest(url,"POST",permanent_url);
		
		return map;
	}	
}
